package com.lemon.kenhnhacvn;

import java.util.ArrayList;

import org.kobjects.base64.Base64;

import saucaca.Object.PlaylistObject;
import saucaca.Object.SongObject;
import saucaca.Service.MusicService;
import saucaca.Service.MusicService.MediaPlayerState;
import saucaca.Service.PlaylistManager;
import saucaca.Service.PlaylistManager.RepeatMode;
import saucaca.Service.Singleton;
import saucaca.Util.CirclePageIndicator;
import saucaca.Util.TagName;
import saucaca.Util.UtilMusic;
import saucaca.fragment.CommentFragment;
import saucaca.fragment.MainListeningPlaylistQueue;
import saucaca.fragment.MainListteningContent;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;


public class PlayActivity extends FragmentActivity {
	String TAG = PlayActivity.class.getSimpleName();
	  
	  ImageView imgMenuNavigate;
		private TextView playing_Title, playing_Artist;
		private TextView currentPlayingPosition;
		private TextView currentDuration;
		private ImageView bt_Play;
		private ImageView bt_Next;
		private ImageView bt_Previous;
		private ImageView bt_ShuffleToggle;
		private ImageView bt_RepeatToggle;

		private SeekBar songProgressBar;
		private boolean songProgressBarIsBeingTouch;
		public PlaylistManager mPlaylistMgr;
		private MusicServiceStatusReceiver mStatusReceiver;

		ViewPager viewPager;
		CirclePageIndicator mIndicator;
		OfflineTabPageAdapter TabAdapter;
		
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        overridePendingTransition(R.anim.push_bottom_in, R.anim.main);
        initView();
    }
    
    private void initView() {
    	imgMenuNavigate=(ImageView) findViewById(R.id.menu_top_navigation_back);
    	imgMenuNavigate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		bt_Play = (ImageView) findViewById(R.id.listening_control_imagePlayPause);
		bt_Previous = (ImageView) findViewById(R.id.listening_control_imagePrevious);
		bt_Next = (ImageView) findViewById(R.id.listening_control_imageNext);
		bt_ShuffleToggle = (ImageView) findViewById(R.id.listening_control_imageShuffle);
		bt_RepeatToggle = (ImageView) findViewById(R.id.listening_control_imageRepeat);
		playing_Title = (TextView) findViewById(R.id.title_of_nameSong);
		playing_Artist = (TextView) findViewById(R.id.title_of_artist);
		currentPlayingPosition = (TextView) findViewById(R.id.listening_control_textbufferStart);
		currentDuration = (TextView) findViewById(R.id.listening_control_textbufferEnd);

		songProgressBarIsBeingTouch = false;
		songProgressBar = (SeekBar) findViewById(R.id.listening_control_seekBars);
		songProgressBar.setMax(100);
		songProgressBar.setOnSeekBarChangeListener(songProgressBar_changeListener);

		bt_Previous.setOnClickListener(bt_Previous_click);
		bt_Play.setOnClickListener(bt_Play_click);
		bt_Next.setOnClickListener(bt_Next_click);
		bt_ShuffleToggle.setOnClickListener(bt_ShuffleToggle_Click);
		bt_RepeatToggle.setOnClickListener(bt_RepeatToggle_Click);
		viewPager = (ViewPager) findViewById(R.id.main_view_pager);
		mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
		mIndicator.setCentered(true);
    }
    
	/**
	 * Restore preferences
	 */
	private void restorePreferences() {
		SharedPreferences sp = PlayActivity.this.getSharedPreferences(MusicService.PREF_NAME, 0);

		// shuffle mode
		setShuffle(sp.getBoolean(MusicService.SETTING_SHUFFLE, false), false);

		// repeat mode
		String rp = sp.getString(MusicService.SETTING_REPEAT, RepeatMode.NoRepeat.toString());
		setRepeatMode(RepeatMode.valueOf(rp), true);
	}

	/**
	 * Save the preferences
	 */
	private void savePreferences() {
		// Save preference
		SharedPreferences sp = PlayActivity.this.getSharedPreferences(MusicService.PREF_NAME, 0);
		SharedPreferences.Editor ed = sp.edit();
		if(mPlaylistMgr!=null){
		ed.putBoolean(MusicService.SETTING_SHUFFLE, mPlaylistMgr.isShuffle());
		ed.putString(MusicService.SETTING_REPEAT, mPlaylistMgr.getRepeatMode().toString());
		ed.commit();
		}
	}

	// Click listener của nút Next
	public OnClickListener bt_Next_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(MusicService.ACTION_NEXT);
			PlayActivity.this.startService(i);
		}
	};

	// Click listener của nút play
	public OnClickListener bt_Play_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			if (MusicService.mState == MediaPlayerState.Playing) {
				i.setAction(MusicService.ACTION_PAUSE);
			}else{
				i.setAction(MusicService.ACTION_PLAY);
			}
			PlayActivity.this.startService(i);
		}
	};

	// Click listener của nút previous
	public OnClickListener bt_Previous_click = new OnClickListener() {
		public void onClick(View v) {
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(MusicService.ACTION_PREVIOUS);
			PlayActivity.this.startService(i);
		}
	};

	// click listener of shuffletoggle button
	public OnClickListener bt_ShuffleToggle_Click = new OnClickListener() {

		public void onClick(View v) {
			boolean s = mPlaylistMgr.isShuffle();
			setShuffle(!s, true);
		}
	};

	// click listener of repeattoggle
	public OnClickListener bt_RepeatToggle_Click = new OnClickListener() {

		public void onClick(View v) {
			PlaylistManager.RepeatMode rp = mPlaylistMgr.getRepeatMode();

			if (rp == RepeatMode.NoRepeat)
				setRepeatMode(RepeatMode.RepeatAll, true);
			else if (rp == RepeatMode.RepeatAll)
				setRepeatMode(RepeatMode.RepeatOne, true);
			else
				setRepeatMode(RepeatMode.NoRepeat, true);
		}
	};

	/**
	 * Set repeat mode for mainplayer, update UI also
	 * 
	 * @param rp
	 * @param needtoast
	 *            if true, toast will be shown
	 */
	private void setRepeatMode(RepeatMode rp, boolean needtoast) {
		if (mPlaylistMgr == null){
			return;
		}
		mPlaylistMgr.setRepeatMode(rp);
		if(bt_RepeatToggle!=null){
			if (rp == RepeatMode.RepeatAll) {
				if (needtoast)
					bt_RepeatToggle.setImageResource(R.drawable.ctbh_iconright_click);
	
			} else if (rp == RepeatMode.RepeatOne) {
				if (needtoast)
					bt_RepeatToggle.setImageResource(R.drawable.ctbh_iconright_click_one);
	
			} else {
				if (needtoast)
					bt_RepeatToggle.setImageResource(R.drawable.ctbh_iconright);
			}
		}
	}

	/**
	 * set shuffle mode for mainplayer, update also the UI
	 * 
	 * @param s
	 *            Shuffle
	 * @param needtoast
	 *            if true, toast will be shown
	 */
	private void setShuffle(boolean s, boolean needtoast) {
		if (mPlaylistMgr == null)
			return;
		mPlaylistMgr.setShuffle(s);
		if (s) {
			if (needtoast)
				bt_ShuffleToggle.setImageResource(R.drawable.ctbh_iconleft_click);
		} else {
			if (needtoast)
				bt_ShuffleToggle.setImageResource(R.drawable.ctbh_iconleft);
		}
	}

	// Seekbar change listener
	private OnSeekBarChangeListener songProgressBar_changeListener = new OnSeekBarChangeListener() {

		public void onStartTrackingTouch(SeekBar seekBar) {
			songProgressBarIsBeingTouch = true;
		}

		public void onStopTrackingTouch(SeekBar seekBar) {
			songProgressBarIsBeingTouch = false;

			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(MusicService.ACTION_SEEK);

			Bundle b = new Bundle();
			b.putInt(MusicService.BKEY_PERCENTAGE, seekBar.getProgress());

			i.putExtras(b);
			PlayActivity.this.startService(i);
		}

		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

		}
	};

//	@Override
//	public void onPause() {
//		PlayActivity.this.unregisterReceiver(mStatusReceiver);
//		savePreferences();
//
//		if (MusicService.getState() != MediaPlayerState.Playing) {
//			Intent i = new Intent();
//			i.setClass(PlayActivity.this, MusicService.class);
//			PlayActivity.this.stopService(i);
//		}
//
//		super.onPause();
//	}

	@Override
	protected void onStart() {
		
		// register music service status reciever
		try {
			mStatusReceiver = new MusicServiceStatusReceiver();
			IntentFilter filter = new IntentFilter();
			filter.addAction(MusicService.STATUS_BC_NOW_PLAYING);
			filter.addAction(MusicService.STATUS_BC_PLAYTIME);
			filter.addAction(MusicService.STATUS_BC_ALL);
			filter.addAction(MusicService.STATUS_BC_PLAYMODE);
			filter.addAction(MusicService.STATUS_BC_NOWPLAYING_PLAYLIST);
			registerReceiver(mStatusReceiver, filter);
			// request status
			Intent i = new Intent(
			         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
			i.setPackage("com.lemon.kenhnhacvn");
			i.setAction(MusicService.REQUEST_STATUS);
			PlayActivity.this.startService(i);
		} catch (Exception e) {
		}
		super.onStart();
	}

//	@Override
//	protected void onStop() {
//		super.onStop();
//		savePreferences();
//	}

	@Override
	protected void onResumeFragments() {
		mStatusReceiver = new MusicServiceStatusReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicService.STATUS_BC_NOW_PLAYING);
		filter.addAction(MusicService.STATUS_BC_PLAYTIME);
		filter.addAction(MusicService.STATUS_BC_ALL);
		filter.addAction(MusicService.STATUS_BC_PLAYMODE);
		filter.addAction(MusicService.STATUS_BC_NOWPLAYING_PLAYLIST);
		PlayActivity.this.registerReceiver(mStatusReceiver, filter);

		// request status
//		Intent i = new Intent();
		Intent i = new Intent(
		         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
		i.setPackage("com.lemon.kenhnhacvn");
		i.setAction(MusicService.REQUEST_STATUS);
		PlayActivity.this.startService(i);
		mPlaylistMgr=MusicService.getPlaylistManager();
		restorePreferences();
		super.onResumeFragments();
	}

	private class MusicServiceStatusReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Bundle b = intent.getExtras();
			Singleton singleton = Singleton.getInstance();
			if (mPlaylistMgr == null) {
				mPlaylistMgr = new PlaylistManager(singleton.getNowPlayingList());
//				restorePreferences();
			}
			if (action.equals(MusicService.STATUS_BC_ALL)) {
				// play-mode buttons
				if (mPlaylistMgr != null) {
					setShuffle(mPlaylistMgr.isShuffle(), false);
					setRepeatMode(mPlaylistMgr.getRepeatMode(), false);
				}
			}
			// Kiểm tra action để thể hiện tên bài hát
			if (action.equals(MusicService.STATUS_BC_NOW_PLAYING) || action.equals(MusicService.STATUS_BC_ALL)) {
				SongObject si = singleton.getCurrentSongObject();
				if (si != null) {
					if (singleton != null) {
					}
					updateBarcontrol(si);
					songProgressBar.setEnabled(true);
				} else {
					playing_Title.setText("");
					playing_Artist.setText("");


					currentPlayingPosition.setText("");
					currentDuration.setText("");
					songProgressBar.setEnabled(false);
				}
			}

			if (action.equals(MusicService.STATUS_BC_PLAYTIME) || action.equals(MusicService.STATUS_BC_ALL)) {
				// cap nhat seek bar
				int pos = b.getInt(MusicService.BKEY_CURSONG_POSITION);
				int len = b.getInt(MusicService.BKEY_CURSONG_DURATION);
				currentPlayingPosition.setText(UtilMusic.milliSecondsToTimer(pos));
				currentDuration.setText(UtilMusic.milliSecondsToTimer(len));
				if (!songProgressBarIsBeingTouch) {
					songProgressBar.setProgress(UtilMusic.getProgressPercentage(pos, len));
					Drawable ii = getResources().getDrawable(R.drawable.ctbh_icon_timeline);
					songProgressBar.setThumb(ii);
				}
			}

			// Update state of play/pause button
			MediaPlayerState mState = (MediaPlayerState) b.getSerializable(MusicService.BKEY_STATE);
			if (mState == MediaPlayerState.Paused || mState == MediaPlayerState.Stopped) {
				bt_Play.setImageResource(R.drawable.ctbh_pause_icon);
			} else if (mState == MediaPlayerState.Playing) {
				bt_Play.setImageResource(R.drawable.ctbh_play_icon);
			}
		}
	}

	public void SendPlaylistAndplay(ArrayList<SongObject> listSongs, int index) {
		if (mPlaylistMgr != null) {
			if (!BaseEngine.compareList(mPlaylistMgr.getArrayList(), listSongs)) {
				mPlaylistMgr.setArrayList(listSongs);
				send();
				play(listSongs, index);
			} else {
				play(listSongs, index);
			}
		} else {
			mPlaylistMgr = new PlaylistManager(listSongs);
			send();
			play(listSongs, index);
		}
	}

	private void send() {
		Singleton s = Singleton.getInstance();
		s.setPlaylistManager(mPlaylistMgr);
		s.setNowPlayingList(mPlaylistMgr.getArrayList());
		Intent i = new Intent(
		         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
		i.setPackage("com.lemon.kenhnhacvn");
		i.setAction(MusicService.SUPPLY_PLAYLIST);
		PlayActivity.this.startService(i);
	}

	public void play(ArrayList<SongObject> listSongs, int index) {
		SongObject si = (SongObject) listSongs.get(index);
		Singleton singleton = Singleton.getInstance();
		singleton.setCurrentSongObject(si);
		singleton.setCurrentIndex(index);
		updateBarcontrol(si);
		Intent i1 = new Intent(
		         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
		i1.setPackage("com.lemon.kenhnhacvn");
		i1.setAction(MusicService.ACTION_PLAY_SPECIFIC_SONG);
		PlayActivity.this.startService(i1);
	}
	public void play( int index) {
		SongObject si = (SongObject) mPlaylistMgr.getArrayList().get(index);
		Singleton singleton = Singleton.getInstance();
		singleton.setCurrentSongObject(si);
		singleton.setCurrentIndex(index);
		updateBarcontrol(si);
		Intent i1 = new Intent(
		         new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
		i1.setPackage("com.lemon.kenhnhacvn");
		i1.setAction(MusicService.ACTION_PLAY_SPECIFIC_SONG);
		PlayActivity.this.startService(i1);
	}
	public void updateBarcontrol(SongObject si) {
		playing_Title.setText(si.getTXNAME());
		playing_Artist.setText(si.getNAME_SINGERS());
		if (TabAdapter == null) {
				MainListeningPlaylistQueue playlistQueue = MainListeningPlaylistQueue.newInstance(Singleton.getInstance().getNowPlayingList());
				MainListteningContent listteningContent =MainListteningContent.newInstance(si);
//				playlistQueue.adapterQueueAdapter.setPotitionIndicator(Singleton.getInstance().index);
				CommentFragment frComment = CommentFragment.newInstance(si, TagName.Comment_typeSong);
				TabAdapter = new OfflineTabPageAdapter(getSupportFragmentManager(), playlistQueue, listteningContent, frComment);
				viewPager.setAdapter(TabAdapter);
				mIndicator.setViewPager(viewPager);
				viewPager.setCurrentItem(1);
		} else {
			TabAdapter.listQueue.update(Singleton.getInstance().getNowPlayingList(), Singleton.getInstance().getCurrentIndex());
			TabAdapter.frMain.update(si);
			TabAdapter.frComment.update(si, "1");
		}
	}

	public void onPlayListClick(View v) {
		if (mPlaylistMgr != null)
			ShowPlayListSongQueue(PlayActivity.this, mPlaylistMgr.getArrayList());
	}

	public void ShowPlayListSongQueue(final Activity a, final ArrayList<SongObject> playlist) {
		AlertDialog.Builder builder = new AlertDialog.Builder(a);
		builder.setTitle("Danh sách phát");

		if (playlist == null || playlist.size() == 0) {
			Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			return;
		}
		String[] array = new String[playlist.size()];
		for (int i = 0; i < playlist.size(); i++) {
			array[i] = playlist.get(i).getTXNAME();
		}

		builder.setItems(array, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int position) {
				play(playlist, position);
			}
		});
		builder.create().show();
	}

	public void ShowPlayList(final Activity a, final ArrayList<PlaylistObject> playlist) {
		AlertDialog.Builder builder = new AlertDialog.Builder(a);
		builder.setTitle("Danh sách phát");

		if (playlist == null || playlist.size() == 0) {
			Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			return;
		}
		String[] array = new String[playlist.size()];
		for (int i = 0; i < playlist.size(); i++) {
			array[i] = playlist.get(i).getTXNAME();
		}

		builder.setItems(array, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int position) {
				Toast.makeText(a, "Trống!", Toast.LENGTH_SHORT).show();
			}
		});
		builder.create().show();
	}
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		 overridePendingTransition(R.anim.main, R.anim.push_bottom_out);
	}

	public void showRingtone(){
		if (mPlaylistMgr.getCurrentSong()!=null) {
			Intent returnIntent = new Intent();
			returnIntent.putExtra("result", mPlaylistMgr.getCurrentSong());
			setResult(RESULT_OK,returnIntent);
		}
		onBackPressed();
	}
	public class OfflineTabPageAdapter extends FragmentStatePagerAdapter {
		public MainListeningPlaylistQueue listQueue = null;
		public MainListteningContent frMain = null;
		public CommentFragment frComment = null;

		public OfflineTabPageAdapter(FragmentManager fm, MainListeningPlaylistQueue listView, MainListteningContent frMain, CommentFragment frComment) {
			super(fm);
			this.listQueue = listView;
			this.frMain = frMain;
			this.frComment = frComment;
			
			if(listView==null) Log.e("", "MainListeningPlaylistQueue: null111111111111111111111");
			if(listView==null) Log.e("", "MainListteningContent: null2222222222222222");
			if(listView==null) Log.e("", "CommentFragment: null3333333333333333");
				
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return null;
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public Fragment getItem(int i) {
			switch (i) {
			case 0:
				return listQueue;
			case 2:
				return frComment;
			default:
				return frMain;
			}
		}
	}
}
